package com.cy.pj.sys.service.realm;

/**
 * @author 张琪
 * @date 2020/11/19
 * @describe
 */

import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ShiroUserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;
    @Autowired
    private SysMenuDao sysMenuDao;

    /**
     * 设置凭证匹配器(与用户添加操作, 使用相同的加密算法)
     * @param credentialsMatcher
     */
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher cMathcer =
                new HashedCredentialsMatcher();
        cMathcer.setHashAlgorithmName("MD5");
        cMathcer.setHashIterations(1);
        super.setCredentialsMatcher(cMathcer);

    }

    /*负责授权信息的获取与封装*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        1. 获取登陆用户
        SysUser user = (SysUser) principals.getPrimaryPrincipal();

//        2, 基于登录用户查询用户对应的角色id并校验
        List<Integer> roleIds = sysUserRoleDao.findRoleIdsByUserId(user.getId());
        if(roleIds == null || roleIds.size() == 0)
            throw new AuthorizationException();

//        3. 基于角色id 查找菜单id并校验
        List<Integer> menuIds = sysRoleMenuDao.findMenuIdsByIds(roleIds);
        if(menuIds == null || menuIds.size() == 0)
            throw new AuthorizationException();

//        4. 基于菜单id找到授权标识并验证
        List<String> permissions = sysMenuDao.findPermissionsByIds(menuIds);
        if(permissions == null || permissions.size() == 0)
            throw new AuthorizationException();

//        5. 封装用户信息并返回(交给SecurityManager来处理//SecurityManager对象来完成认证和授权)
        SimpleAuthorizationInfo info =
                new SimpleAuthorizationInfo();
        Set<String> set = new HashSet<>();
        for(String s : permissions){
            if(!StringUtils.isEmpty(s)){
                set.add(s);
            }
        }
        info.setStringPermissions(set); //参数为Set<>


//        SysRoleMenu sysRoleMenu = sysRoleMenuDao.findMenuIdsById();

        return info;
    }

    /*负责认证信息的获取与封装*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

//        1. 获取用户登陆信息(用户名, 密码)
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//        2. 基于用户名查询数据库
        String username = upToken.getUsername();
        SysUser sysUser = sysUserDao.findUserByUserName(username);
        System.err.println(sysUser);
        if(sysUser == null)
            throw new UnknownAccountException("该用户不存在");
        if(sysUser.getValid() == 0)
            throw new LockedAccountException("该用户已被封禁");


//        5.封装信息并返回
        /*按照指定编码, 做编码处理*/
        ByteSource credentialsSalt = ByteSource.Util.bytes(sysUser.getSalt());

        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(
                        sysUser,        //principle 传用户名
                        sysUser.getPassword(),  //credentials 凭证
                        credentialsSalt,//ByteSource 凭证盐
                        getName()
                );
        return info;
    }



}
